package com.scu.phototab.config;

import com.google.gson.Gson;
import com.scu.phototab.enums.ResponseEnum;
import com.scu.phototab.util.ResponseUtil;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by tianfei on 2017/4/12.
 */

@Configuration
public class RequestFilter{

    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }

    //注册url请求过滤器
    @Bean
    public FilterRegistrationBean servletRequestRegistrationBean() {
        FilterRegistrationBean bean= new FilterRegistrationBean(new filter());
        bean.addUrlPatterns("/session/*");
        bean.setOrder(Integer.MAX_VALUE-1);
        return bean;
    }

    class filter implements Filter{

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {}

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest httpRequest;

            try {
                httpRequest=(HttpServletRequest)servletRequest;
            }catch (Exception e){
                errReturn(servletResponse, ResponseEnum.ONLY_HTTP_ALLOWED);
                return;
            }

            if (httpRequest.getRequestURI().contains("/user/pass/")){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }

            if (!"POST".equals(httpRequest.getMethod())){
                errReturn(servletResponse, ResponseEnum.ONLY_POST_SUPPORTED);
            }else {
                String url=httpRequest.getRequestURL().toString();
                if (url.endsWith(".action")){
                    filterChain.doFilter(servletRequest,servletResponse);
                }else {
                    errReturn(servletResponse, ResponseEnum.BAD_URL_FORMAT);
                }
            }
        }

        @Override
        public void destroy() {}

        private void errReturn(ServletResponse servletResponse,ResponseEnum e) throws  IOException{
            servletResponse.setContentType("application/json;charset=utf-8");
            String res=new Gson().toJson(ResponseUtil.error(e));
            servletResponse.getWriter().append(res);
        }
    }
}
